package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class EmployeeFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        boolean flag = false;
        for (String loginUrl : loginUrls) {
            boolean match = antPathMatcher.match(loginUrl, requestURI);
            if (match) {
                flag = true;
            }
        }
        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute("employee") != null) {
            Employee employee = (Employee) request.getSession().getAttribute("employee");
            Long id = employee.getId();
            log.info("id是：" + id);
            BaseContext.setThreadLocal(id);
            filterChain.doFilter(request, response);
            BaseContext.reless();
            return;
        }


        if (request.getSession().getAttribute("user") != null) {
            User user = (User) request.getSession().getAttribute("user");
            Long id = user.getId();
            log.info("id是：" + id);
            BaseContext.setThreadLocal(id);
            filterChain.doFilter(request, response);
            BaseContext.reless();
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }
}
